#include "stdafx.h"
#include "./luaregistration.h"
#include "./luamodule.h"

LuaModule::LuaModule(lua_State* luaState, const char * name)
: Scope(new ModuleRegistration(name))
, m_luaState(luaState)
, m_name(name)
{
    if (name)
    {
        lua_getglobal(luaState, name);
        if (lua_isnil(luaState, -1))
        {
            lua_pop(luaState, 1);
            lua_newtable(luaState);
            lua_setglobal(luaState, name);
        }
        else
        {
            lua_pop(luaState, 1);
        }
    }
}

LuaModule::~LuaModule()
{
}

void LuaModule::operator[](const Scope &scope) const
{
    if (m_name)
    {
        lua_getglobal(m_luaState, m_name);
        scope.Register(m_luaState, false);
        lua_pop(m_luaState, 1);
    }
    else
    {
        scope.Register(m_luaState, true);
    }
}